// pages/room-detail/index.js
Page({
  data: {
    roomId: '',
    isEdit: false,
    loading: false,
    
    // 表单数据
    room: '', // 房间号
    area: '', // 面积
    roomType: '', // 户型：一室一厅一卫、两室一厅一卫
    propertyFee: '', // 物业费
    province: '四川省',
    city: '成都市',
    district: '新都区',
    street: '斑竹园街道',
    address: '鸿发路488号1栋17层',
    status: 'available', // 房间状态
    
    // 户型选项
    roomTypeOptions: ['一室一厅一卫', '两室一厅一卫'],
    
    // 房间状态选项
    statusOptions: ['available', 'rented', 'maintenance'],
    statusTexts: {
      'available': '可用',
      'rented': '已租',
      'maintenance': '维护中'
    },
    statusTextsArray: ['可用', '已租', '维护中'],
    
    // 当前选中的索引
    roomTypeIndex: 0,
    statusIndex: 0
  },

  onLoad(options) {
    if (options.roomId) {
      this.setData({ 
        roomId: options.roomId,
        isEdit: true
      });
      this.loadRoomInfo();
    } else {
      this.setData({ isEdit: false });
    }
  },

  // 加载房间信息
  async loadRoomInfo() {
    this.setData({ loading: true });
    
    try {
      const res = await wx.cloud.callFunction({
        name: 'room',
        data: {
          apiType: 'getRoomInfo',
          roomId: this.data.roomId
        }
      });

      if (res.result.res.code === 200) {
        const roomInfo = res.result.res.data;
        const roomType = roomInfo.roomType || '';
        const roomTypeIndex = this.data.roomTypeOptions.indexOf(roomType);
        
        const status = roomInfo.status || 'available';
        const statusIndex = this.data.statusOptions.indexOf(status);
        
        this.setData({
          room: roomInfo.room || '',
          area: roomInfo.area || '',
          roomType: roomType,
          propertyFee: roomInfo.propertyFee || '',
          province: roomInfo.province || '四川省',
          city: roomInfo.city || '成都市',
          district: roomInfo.district || '新都区',
          street: roomInfo.street || '斑竹园街道',
          address: roomInfo.address || '鸿发路488号1栋17层',
          status: status,
          roomTypeIndex: roomTypeIndex >= 0 ? roomTypeIndex : 0,
          statusIndex: statusIndex >= 0 ? statusIndex : 0,
          loading: false
        });
      } else {
        wx.showToast({
          title: res.result.res.msg || '加载失败',
          icon: 'none'
        });
        this.setData({ loading: false });
      }
    } catch (error) {
      console.error('加载房间信息失败:', error);
      wx.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      });
      this.setData({ loading: false });
    }
  },

  // 输入事件
  onRoomInput(e) {
    this.setData({ room: e.detail.value });
  },

  onAreaInput(e) {
    this.setData({ area: e.detail.value });
  },

  onRoomTypeChange(e) {
    const index = parseInt(e.detail.value);
    const selectedType = this.data.roomTypeOptions[index];
    this.setData({ 
      roomType: selectedType,
      roomTypeIndex: index
    });
  },

  onPropertyFeeInput(e) {
    this.setData({ propertyFee: e.detail.value });
  },

  onProvinceInput(e) {
    this.setData({ province: e.detail.value });
  },

  onCityInput(e) {
    this.setData({ city: e.detail.value });
  },

  onDistrictInput(e) {
    this.setData({ district: e.detail.value });
  },

  onStreetInput(e) {
    this.setData({ street: e.detail.value });
  },

  onAddressInput(e) {
    this.setData({ address: e.detail.value });
  },

  onStatusChange(e) {
    const index = parseInt(e.detail.value);
    const selectedStatus = this.data.statusOptions[index];
    this.setData({ 
      status: selectedStatus,
      statusIndex: index
    });
  },

  // 跳转到物品核对页面
  goToRoomItems() {
    if (!this.data.roomId) {
      wx.showToast({
        title: '房间ID不存在',
        icon: 'none'
      });
      return;
    }
    wx.navigateTo({
      url: `/pages/room-items/index?roomId=${this.data.roomId}`
    });
  },

  // 表单验证
  validateForm() {
    if (!this.data.room || this.data.room.trim() === '') {
      wx.showToast({
        title: '请输入房间号',
        icon: 'none'
      });
      return false;
    }

    if (!this.data.area || this.data.area.trim() === '') {
      wx.showToast({
        title: '请输入面积',
        icon: 'none'
      });
      return false;
    }

    return true;
  },

  // 保存房间信息
  async saveRoom() {
    if (!this.validateForm()) {
      return;
    }

    wx.showLoading({ title: '保存中...' });

    try {
      const apiType = this.data.isEdit ? 'updateRoom' : 'addRoom';
      const data = {
        apiType: apiType,
        room: this.data.room,
        area: this.data.area,
        roomType: this.data.roomType,
        propertyFee: this.data.propertyFee,
        province: this.data.province,
        city: this.data.city,
        district: this.data.district,
        street: this.data.street,
        address: this.data.address,
        status: this.data.status
      };

      if (this.data.isEdit) {
        data.roomId = this.data.roomId;
      }

      const res = await wx.cloud.callFunction({
        name: 'room',
        data: data
      });

      wx.hideLoading();

      if (res.result.res.code === 200) {
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        });
        
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      } else {
        wx.showToast({
          title: res.result.res.msg || '保存失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('保存房间信息失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: '保存失败，请重试',
        icon: 'none'
      });
    }
  },

  // 删除房间
  async deleteRoom() {
    if (!this.data.isEdit || !this.data.roomId) {
      return;
    }

    const roomName = this.data.room || '房间';

    wx.showModal({
      title: '确认删除',
      content: `确定要删除"${roomName}"吗？`,
      success: async (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '删除中...' });
          
          try {
            const deleteRes = await wx.cloud.callFunction({
              name: 'room',
              data: {
                apiType: 'deleteRoom',
                roomId: this.data.roomId
              }
            });

            wx.hideLoading();

            if (deleteRes.result.res.code === 200) {
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              });
              
              setTimeout(() => {
                wx.navigateBack();
              }, 1500);
            } else {
              wx.showToast({
                title: deleteRes.result.res.msg || '删除失败',
                icon: 'none'
              });
            }
          } catch (error) {
            console.error('删除房间失败:', error);
            wx.hideLoading();
            wx.showToast({
              title: '删除失败，请重试',
              icon: 'none'
            });
          }
        }
      }
    });
  }
});

